<!-- 个人资料 -->
<template>
    <div class="user-setting">
        <div class="flex gap-4">
            <!-- 左侧侧栏 -->
            <div class="w-64">
                <el-card class="!border-none" shadow="never">
                    <div class="space-y-2">
                        <div
                            v-for="item in menuItems"
                            :key="item.key"
                            :class="[
                                'p-3 rounded cursor-pointer transition-colors',
                                activeTab === item.key
                                    ? 'bg-blue-50 text-blue-600'
                                    : 'hover:bg-gray-50'
                            ]"
                            @click="activeTab = item.key"
                        >
                            {{ item.label }}
                        </div>
                    </div>
                </el-card>
            </div>

            <!-- 右侧内容区域 -->
            <div class="flex-1">
                <el-card class="!border-none" shadow="never">
                    <!-- 我的账户 -->
                    <div v-if="activeTab === 'account'">
                        <h3 class="text-lg font-medium mb-4">我的账户</h3>
                        <el-form
                            ref="accountFormRef"
                            class="ls-form"
                            :model="accountForm"
                            :rules="accountRules"
                            label-width="100px"
                        >
                            <el-form-item label="头像：" prop="avatar">
                                <material-picker v-model="accountForm.avatar" :limit="1" />
                            </el-form-item>

                            <el-form-item label="账号：" prop="account">
                                <div class="w-80">
                                    <el-input v-model="accountForm.account" disabled />
                                </div>
                            </el-form-item>

                            <el-form-item label="名称：" prop="name">
                                <div class="w-80">
                                    <el-input v-model="accountForm.name" placeholder="请输入名称" />
                                </div>
                            </el-form-item>
                        </el-form>
                        <footer-btns>
                            <el-button type="primary" @click="handleAccountSubmit">保存</el-button>
                        </footer-btns>
                    </div>

                    <!-- 修改登录密码 -->
                    <div v-if="activeTab === 'password'">
                        <h3 class="text-lg font-medium mb-4">修改登录密码</h3>
                        <el-form
                            ref="passwordFormRef"
                            class="ls-form"
                            :model="passwordForm"
                            :rules="passwordRules"
                            label-width="100px"
                        >
                            <el-form-item label="当前密码：" prop="password_old">
                                <div class="w-80">
                                    <el-input
                                        v-model.trim="passwordForm.password_old"
                                        placeholder="请输入当前密码"
                                        type="password"
                                        show-password
                                    />
                                </div>
                            </el-form-item>

                            <el-form-item label="新的密码：" prop="password">
                                <div class="w-80">
                                    <el-input
                                        v-model.trim="passwordForm.password"
                                        placeholder="请输入新的密码"
                                        type="password"
                                        show-password
                                    />
                                </div>
                            </el-form-item>

                            <el-form-item label="确定密码：" prop="password_confirm">
                                <div class="w-80">
                                    <el-input
                                        v-model.trim="passwordForm.password_confirm"
                                        placeholder="请再次输入新密码"
                                        type="password"
                                        show-password
                                    />
                                </div>
                            </el-form-item>
                        </el-form>
                        <footer-btns>
                            <el-button type="primary" @click="handlePasswordSubmit">修改密码</el-button>
                        </footer-btns>
                    </div>

                    <!-- 登录记录 -->
                    <div v-if="activeTab === 'logs'">
                        <h3 class="text-lg font-medium mb-4">登录记录</h3>
                        <el-table :data="loginLogs" style="width: 100%">
                            <el-table-column prop="login_time" label="登录时间" width="180" />
                            <el-table-column prop="login_address" label="登录地址" />
                            <!-- 可以根据API返回的字段添加更多列 -->
                        </el-table>
                        <div class="mt-4 flex justify-center">
                            <el-button 
                                v-if="hasMoreLogs"
                                type="primary"
                                :loading="loadingLogs"
                                @click="loadMoreLogs"
                            >
                                加载更多
                            </el-button>
                            <div v-else-if="loginLogs.length > 0" class="text-gray-500">
                                没有更多记录了
                            </div>
                            <div v-else class="text-gray-500">
                                暂无登录记录
                            </div>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts" name="userSetting">
import type { FormInstance } from 'element-plus'
import { setUserInfo, getUserLoginLogs } from '@/api/user'
import useUserStore from '@/stores/modules/user'
import feedback from '@/utils/feedback'

const accountFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const userStore = useUserStore()

console.log('用户的信息:', userStore.userInfo);

// 菜单项
const menuItems = [
    { key: 'account', label: '我的账户' },
    { key: 'password', label: '修改密码' },
    { key: 'logs', label: '登录记录' }
]

// 当前激活的标签
const activeTab = ref('account')

// 我的账户表单
const accountForm = reactive({
    avatar: '',
    account: '',
    name: '',
    total_cost_amount: ''
})

// 修改密码表单
const passwordForm = reactive({
    password_old: '',
    password: '',
    password_confirm: ''
})

// 登录记录相关
const loadingLogs = ref(false)
const hasMoreLogs = ref(true)
const currentPage = ref(1)
const pageSize = ref(2)
const loginLogs = ref<Array<{ login_time: string; login_address: string }>>([])

// 账户表单校验规则
const accountRules = reactive({
    avatar: [
        {
            required: true,
            message: '头像不能为空',
            trigger: ['change']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ]
})

// 密码表单校验规则
const passwordRules = reactive({
    password_old: [
        {
            required: true,
            message: '请输入当前密码',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入新的密码',
            trigger: ['blur']
        },
        {
            min: 6,
            max: 32,
            message: '密码长度在6到32之间',
            trigger: ['blur']
        }
    ],
    password_confirm: [
        {
            required: true,
            message: '请再次输入新密码',
            trigger: ['blur']
        },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (value !== passwordForm.password) {
                    callback(new Error('两次输入的密码不一样'))
                } else {
                    callback()
                }
            },
            trigger: ['blur']
        }
    ]
})

// 获取用户信息和余额
const getUserInfo = async () => {
    const userInfo = userStore.userInfo
    accountForm.avatar = userInfo.avatar || ''
    accountForm.account = userInfo.account || ''
    accountForm.name = userInfo.name || ''
}

// 保存账户信息
const handleAccountSubmit = async () => {
    await accountFormRef.value?.validate()
    await setUserInfo({
        avatar: accountForm.avatar,
        name: accountForm.name
    })
    userStore.getUserInfo()
    feedback.msgSuccess('保存成功')
}

// 修改密码
const handlePasswordSubmit = async () => {
    await passwordFormRef.value?.validate()
    
    await setUserInfo({
        password_old: passwordForm.password_old,
        password: passwordForm.password,
        password_confirm: passwordForm.password_confirm
    })
    
    // 清空密码表单
    passwordForm.password_old = ''
    passwordForm.password = ''
    passwordForm.password_confirm = ''
    
    feedback.msgSuccess('密码修改成功')
}

// 获取登录记录
const getLoginLogs = async () => {
    try {
        loadingLogs.value = true
        
        console.log('开始获取登录记录，页码：', currentPage.value);
        
        // 调用API获取登录记录
        const res = await getUserLoginLogs({
            page: currentPage.value,
            page_size: pageSize.value
        })
        
        
        // 直接获取数据，不再使用可选链
        let newData = [];
        let totalCount = 0;

        
        // 确保res和res.data存在
        if (res && res.lists) {
            // 直接访问lists和count，不再使用可选链
            newData = res.lists || [];
            totalCount = typeof res.count === 'number' ? res.count : 0;
        }
        
        
        // 确保newData是数组
        if (Array.isArray(newData) && newData.length > 0) {
            // 直接赋值确保响应式更新
            if (currentPage.value === 1) {
                loginLogs.value = [...newData];
            } else {
                loginLogs.value = [...loginLogs.value, ...newData];
            }
            console.log('更新后的登录记录：', loginLogs.value);
        } else {
            console.log('没有新数据或数据不是数组');
        }
        
        // 判断是否还有更多数据
        hasMoreLogs.value = loginLogs.value.length < totalCount;
        console.log('是否有更多数据：', hasMoreLogs.value);
    
    } catch (error) {
        console.error('获取登录记录失败:', error);
        feedback.msgError('获取登录记录失败');
    } finally {
        loadingLogs.value = false;
    }
}

// 加载更多记录
const loadMoreLogs = async () => {
    if (loadingLogs.value) return // 避免重复加载
    currentPage.value++
    await getLoginLogs()
}

// 初始化登录记录
const initLoginLogs = async () => {
    currentPage.value = 1
    loginLogs.value = []
    hasMoreLogs.value = true
    await getLoginLogs()
}

// 初始化
getUserInfo()
initLoginLogs()
</script>

<style lang="scss" scoped>
.user-setting {
    padding: 20px;
}
</style>